package ru.onlinestore.mobile.ui.main

import ru.onlinestore.mobile.domain.usecase.GetProductListUseCase
import ru.onlinestore.mobile.ui.entities.states.MainState
import androidx.lifecycle.ViewModel
import ru.onlinestore.mobile.core.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*

class MainViewModel(
    private val getProductListUseCase: GetProductListUseCase
): ViewModel() {

    private val _stateFlow = MutableStateFlow(MainState())
    val stateFlow = _stateFlow.asStateFlow()

    init {
        loadProductList()
    }

    private fun loadProductList() {
        CoroutineScope(Dispatchers.IO).launch {
            getProductListUseCase().collect { result ->
                _stateFlow.update {
                    it.copy(
                        state = result.state
                    )
                }
                when(result) {
                    is Response.Loading -> {
                        _stateFlow.update {
                            it.copy(
                                state = ResponseState.LOADING
                            )
                        }
                    }

                    is Response.Success -> {
                        _stateFlow.update {
                            it.copy(
                                state = ResponseState.SUCCESS,
                                productList = result.data
                            )
                        }
                    }

                    is Response.Error -> {
                        _stateFlow.update {
                            it.copy(
                                state = ResponseState.ERROR,
                                messageError = result.exception.toString()
                            )
                        }
                    }

                    is Response.Empty -> {
                        _stateFlow.update {
                            it.copy(
                                state = ResponseState.EMPTY
                            )
                        }
                    }
                }
            }
        }
    }
}